//
//  YZCoreMotionManager.m
//  VET
//
//  Created by YZ on 2018/8/2.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZCoreMotionManager.h"
#import <CoreMotion/CoreMotion.h>

@interface YZCoreMotionManager()

@property (nonatomic, strong) CMMotionManager *manager;

@property (nonatomic, assign) AVCaptureVideoOrientation currentOrientation;

@end

@implementation YZCoreMotionManager

- (CMMotionManager *)manager
{
    if (!_manager) {
        _manager = [[CMMotionManager alloc] init];
    }
    return _manager;
}

- (void)startUpdateCurrentOrientation
{
    if([self.manager isDeviceMotionAvailable])
    {
        [self.manager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
            if (accelerometerData.acceleration.x < 0.75 && accelerometerData.acceleration.x > -0.75) {
                if (accelerometerData.acceleration.y < 0) {
                    if (self.currentOrientation != AVCaptureVideoOrientationPortrait) {
                        self.currentOrientation = AVCaptureVideoOrientationPortrait;
                    }
                }else if (accelerometerData.acceleration.y >= 0.75){
                    if (self.currentOrientation != AVCaptureVideoOrientationPortraitUpsideDown) {
                        self.currentOrientation = AVCaptureVideoOrientationPortraitUpsideDown;
                    }
                }
            }else if (accelerometerData.acceleration.y < 0.75 && accelerometerData.acceleration.y > -0.75) {
                if (accelerometerData.acceleration.x > 0.75) {
                    if (self.currentOrientation != AVCaptureVideoOrientationLandscapeLeft) {
                        self.currentOrientation = AVCaptureVideoOrientationLandscapeLeft;
                    }
                }else if(accelerometerData.acceleration.x < -0.75){
                    if (self.currentOrientation != AVCaptureVideoOrientationLandscapeRight) {
                        self.currentOrientation = AVCaptureVideoOrientationLandscapeRight;
                    }
                }
            }else {
                return;
            }
        }];
    }
}

- (void)stoptUpdateCurrentOrientation
{
    [self.manager stopAccelerometerUpdates];
}

- (AVCaptureVideoOrientation)getCurrentOrientation
{
    return self.currentOrientation;
}
@end
